package com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.diudiutechnology.www.yadiudiu.util.http.HttpClient;
import com.diudiutechnology.www.yadiudiu.util.http.JsonTools;
import com.diudiutechnology.www.yadiudiu.util.utils.Constant;
import com.diudiutechnology.www.yadiudiu.util.utils.Dialog;
import com.diudiutechnology.www.yadiudiu.util.utils.MyProgressDialog;
import com.diudiutechnology.www.yadiudiu.util.utils.Sundry;
import com.diudiutechnology.www.yadiudiu.util.utils.ToastUtils;
import com.diudiutechnology.www.yadiudiu.util.utils.UserInfoUtils;
import com.diudiutechnology.www.yadiudiu.util.view.pulltorefresh.PullToRefreshBase;
import com.diudiutechnology.www.yadiudiu.util.view.pulltorefresh.PullToRefreshListView;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyActivity.LoginActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyAdapter.WaitingActivityAdapter;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.MerchantsTypeModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.MineFragmentModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.WaitingModel;
import com.diudiutechnology.www.yadiudiu.R;

import org.xutils.common.Callback;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/8/31.
 * 0、待接单  1、已结单  2、已完成
 */

public class WaitingActivity extends Activity implements View.OnClickListener, Callback.CommonCallback<String> {
    @Bind(R.id.retur)
    LinearLayout retur;

    @Bind(R.id.title_center)
    TextView title_center;
    @Bind(R.id.available_layout)//无消息提示
            LinearLayout available_layout;
    ListView listview;
    @Bind(R.id.listview)
    PullToRefreshListView xlistview;
    List<WaitingModel> buycarlist = new ArrayList<>();
    List<WaitingModel> getwjcleaningorder= new ArrayList<>();
    WaitingActivityAdapter adapter;
    private MyProgressDialog mDialog;
    String merchanttype = "";//类型
    String Judge_interface = "0";//判断哪个接口   0、获取数据
    Context context;
    String pos = "0";
    String u_id = "";
    AlertDialog alertDialog;
    // 请求数据
    private int currentPage = 1;

    private boolean mIsStart = true;//判断是否上下加载 true:下拉刷新  false:上拉加载数据
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_waiting);
        ButterKnife.bind(this);
        context = this;
        initView();
    }

    private void initView() {
        retur.setOnClickListener(this);

        listview=xlistview.getRefreshableView();
        // 显示头部出现分割线
        listview.setHeaderDividersEnabled(false);
        // 禁止底部出现分割线
        listview.setFooterDividersEnabled(false);
        listview.setDivider(new ColorDrawable(Color.TRANSPARENT));
        listview.setDividerHeight(0);
        xlistview.setOnRefreshListener(refreshListener);


        if (getIntent() != null) {
            pos = getIntent().getStringExtra("pos");
            u_id = getIntent().getStringExtra("id");
         // u_id="10";
        }
        MineFragmentModel mineFragmentModel = UserInfoUtils.readUserInfo(this);
        merchanttype = mineFragmentModel.getMerchanttype();
     // merchanttype="1";
        if (pos.equals("0")) {
            title_center.setText("待接单");

        } else if (pos.equals("1")) {
            title_center.setText("已接单");

        } else if (pos.equals("2")) {
            title_center.setText("已完成");

        }
        adapter = new WaitingActivityAdapter(context, pos,merchanttype);
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(onItemClick);


        processproofing();

    }

    AdapterView.OnItemClickListener onItemClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent = new Intent(context, OrderDetailsActivity.class);
            intent.putExtra("pos", pos);
            intent.putExtra("u_id",u_id);
            intent.putExtra("ints",i);
            intent.putExtra("data", (Serializable) getwjcleaningorder);
            startActivity(intent);
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.retur:
                finish();
                break;
        }
    }
    private void setLastUpdateTime() {
        String text = formatDateTime(System.currentTimeMillis());
        xlistview.setLastUpdatedLabel(text);
    }
    /**
     * 上拉刷新，下拉获取更多
     */
    PullToRefreshBase.OnRefreshListener refreshListener = new PullToRefreshBase.OnRefreshListener() {

        @Override
        public void onPullDownToRefresh(PullToRefreshBase refreshView) {
            mIsStart = true;
            currentPage = 1;
            if (adapter!=null){
                adapter.emptying();
            }
            Judge_interface = "0";
            processproofing();
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase refreshView) {
            mIsStart = false;
            currentPage++;
            processproofing();
        }
    };
    private String formatDateTime(long time) {
        if (0 == time) {
            return "";
        }
        SimpleDateFormat mDateFormat = new SimpleDateFormat("MM-dd HH:mm");
        return mDateFormat.format(new Date(time));
    }
    private void processdata(){
        mIsStart = true;
        currentPage = 1;
        if (adapter!=null){
            adapter.emptying();
        }
        processproofing();
    }
    //数据
    private void processproofing() {
        if (Sundry.isOpenNetwork(context)) {
            if (Judge_interface=="0"){
                mDialog = new MyProgressDialog(context);
            }
            Judge_interface = "0";
            String Data = "";
            if (merchanttype.equals("1")) {//买房商家
                if (pos.equals("0")) {//订单管理-买房未接单
                    Data = Constant.ORDERMANAGEWJHOUSINGORDER;
                } else if (pos.equals("1")) {//订单管理-买房已接单
                    Data = Constant.ORDERMANAGEWCHOUSINGORDER;
                } else if (pos.equals("2")) {//订单管理-买房已完成
                    Data = Constant.ORDERMANAGEWCHOUSINGORDER;
                }
            } else if (merchanttype.equals("2")) {//购车商家
                if (pos.equals("0")) {//订单管理-购车未接单
                    Data = Constant.ORDERMANAGEZXBUYCARORDER;
                } else if (pos.equals("1")) {//订单管理-购车已接单
                    Data = Constant.ORDERMANAGEWCBUYCARODER;
                } else if (pos.equals("2")) {//订单管理-购车已完成
                    Data = Constant.ORDERMANAGEWCBUYCARODER;
                }
            } else if (merchanttype.equals("3")) {//干洗商家
                if (pos.equals("0")) {//订单管理-干洗未接单
                    Data = Constant.ORDERMANAGEWJCLEANINGORDER;
                } else if (pos.equals("1")) {//订单管理-干洗已接单
                    Data = Constant.ORDERMANAGEYJCLEANINGORDER;
                } else if (pos.equals("2")) {//订单管理-干洗已完成
                    Data = Constant.ORDERMANAGEYWCCLEANINGORDER;
                }
            } else if (merchanttype.equals("4")) {//开锁商家
                if (pos.equals("0")) {//订单管理-开锁未接单
                    Data = Constant.ORDERMANAGEWJUNLOCKINGORDER;
                } else if (pos.equals("1")) {//订单管理-开锁已接单
                    Data = Constant.ORDERMANAGEWCUNLOCKINGORDER;
                } else if (pos.equals("2")) {//订单管理-开锁已完成
                    Data = Constant.ORDERMANAGEWCUNLOCKINGORDER;
                }
            } else if (merchanttype.equals("5")) {//果蔬商家
                if (pos.equals("0")) {//订单管理-蔬果未接单
                    Data = Constant.ORDERMANAGEWJVEGETABLESORDER;
                } else if (pos.equals("1")) {//订单管理-蔬果已接单
                    Data = Constant.ORDERMANAGEYJVEGETABLESORDER;
                } else if (pos.equals("2")) {//订单管理-蔬果已完成
                    Data = Constant.ORDERMANAGECLEANORDERCOMPLETE;
                }
            } else if (merchanttype.equals("6")) {//苦力商家
                if (pos.equals("0")) {//订单管理-苦力未接单
                    Data = Constant.ORDERMANAGEWJCOOLIEORDER;
                } else if (pos.equals("1")) {//订单管理-苦力已接单
                    Data = Constant.ORDERMANAGEYJCOOLIEORDER;
                } else if (pos.equals("2")) {//订单管理-苦力已完成
                    Data = Constant.ORDERMANAGEYJCOOLIEORDER;
                }
            } else if (merchanttype.equals("7")) {//快递商家

            } else if (merchanttype.equals("8")) {//家政商家
                if (pos.equals("0")) {//订单管理-家政未接单
                    Data = Constant.ORDERMANAGEWJHOUSEKEEPINGORDER;
                } else if (pos.equals("1")) {//订单管理-家政已接单
                    Data = Constant.ORDERMANAGEYJHOUSEKEEPINGORDER;
                } else if (pos.equals("2")) {//订单管理-家政已完成
                    Data = Constant.ORDERMANAGEWCHOUSEKEEPINGORDER;
                }
            } else if (merchanttype.equals("9")) {//洗车商家
                if (pos.equals("0")) {//订单管理-洗车未接单
                    Data = Constant.ORDERMANAGEWJORDERWASHCAR;
                } else if (pos.equals("1")) {//订单管理-洗车已接单
                    Data = Constant.ORDERMANAGEWCORDERWASHCAR;
                } else if (pos.equals("2")) {//订单管理-洗车已完成
                    Data = Constant.ORDERMANAGEWCORDERWASHCAR;
                }
            }

            HttpClient.Ordermanage(Data, u_id, currentPage+"",this);
        } else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }

    //接单
    public void processReceipt(final String id) {
        alertDialog = Dialog.phonedialog(context, "是否接受该订单", "接单", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Sundry.isOpenNetwork(context)) {
                    mDialog = new MyProgressDialog(context);
                    Judge_interface = "1";

                    if (merchanttype.equals("1")) {//买房商家

                        HttpClient.Ordermanageaff(Constant.ORDERMANAGEAFFIRMHOUSINGORDER, id, u_id,WaitingActivity.this);
                    } else if (merchanttype.equals("2")) {//购车商家
                        HttpClient.Ordermanageaff(Constant.ORDERMANAGEAFFIRMBUYCAR, id, u_id,WaitingActivity.this);
                    } else if (merchanttype.equals("3")) {//干洗商家
                        HttpClient.orderreceiving(Constant.ORDERMANAGEORDERRECEIVING, id, WaitingActivity.this);
                    } else if (merchanttype.equals("4")) {//开锁商家
                        HttpClient.Ordermanageaff(Constant.ORDERMANAGEAFFIRMLOCK, id, u_id,WaitingActivity.this);
                    } else if (merchanttype.equals("5")) {//果蔬商家

                        HttpClient.orderreceiving(Constant.ORDERMANAGEORDERVEGETABLES, id, WaitingActivity.this);
                    } else if (merchanttype.equals("6")) {//苦力商家

                        HttpClient.Ordermanageaff(Constant.ORDERMANAGEAFFIRMCOOLIE, id, u_id,WaitingActivity.this);

                    } else if (merchanttype.equals("7")) {//快递商家

                    } else if (merchanttype.equals("8")) {//家政商家

                        HttpClient.orderreceiving( Constant.ORDERMANAGERECEIVINGHOUSEKEEPING, id, WaitingActivity.this);
                    } else if (merchanttype.equals("9")) {//洗车商家

                        HttpClient.orderreceiving(Constant.ORDERMANAGEAFFIRMWASHCAR, id, WaitingActivity.this);
                    }


                } else {
                    ToastUtils.Toastshow(context, getResources().getString(R.string.network));
                }
                alertDialog.dismiss();
            }
        }, "确定", "取消");
    }

    //已接单
    public void processoperation(final String id, final String str) {


        String Data = "";
        String title = "";
        String content = "";

        if (merchanttype.equals("1")) {//买房商家

        } else if (merchanttype.equals("2")) {//购车商家

        } else if (merchanttype.equals("3")) {//干洗商家


            if (str.equals("7")) {
                title = "开始洗衣";
                content = "是否开始洗衣";
                Data = Constant.ORDERMANAGELAUNDRY;
            } else  if (str.equals("8")) {
                title = "完成洗衣";
                content = "是否完成洗衣";
                Data = Constant.ORDERMANAGELAUNDRY;
            }else  if (str.equals("11")) {
                title = "确认完成";
                content = "是否确认完成";
                Data = Constant.ORDERMANAGECLEANINGWC;
            }

        } else if (merchanttype.equals("4")) {//开锁商家

        } else if (merchanttype.equals("5")) {//果蔬商家
            if (str.equals("5")) {
                title = "确认取件";
                content = "是否确认取件";
                Data = Constant.ORDERMANAGECOLLECTVEGETABLES;
            } else  if (str.equals("7")) {
                title = "确认完成";
                content = "是否确认完成";
                Data = Constant.ORDERMANAGEVEGETABLESWC;
            }
        } else if (merchanttype.equals("6")) {//苦力商家

        } else if (merchanttype.equals("7")) {//快递商家

        } else if (merchanttype.equals("8")) {//家政商家
            title = "确认完成";
            content = "是否确认完成";
         Data = Constant.ORDERMANAGEAFFIRMHOUSEKEEPING;
        } else if (merchanttype.equals("9")) {//洗车商家

        }
        final String finalData = Data;
        alertDialog = Dialog.phonedialog(context, content, title, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Sundry.isOpenNetwork(context)) {
                    mDialog = new MyProgressDialog(context);
                    Judge_interface = "2";
                    if (merchanttype.equals("1")) {//买房商家

                    } else if (merchanttype.equals("2")) {//购车商家

                    } else if (merchanttype.equals("3")) {//干洗商家
                        if (str.equals("11")){
                            HttpClient.cleaningwc(finalData, id, WaitingActivity.this);
                        }else {
                            HttpClient.laundry(finalData, id, str, WaitingActivity.this);
                        }

                    } else if (merchanttype.equals("4")) {//开锁商家

                    } else if (merchanttype.equals("5")) {//果蔬商家
                        HttpClient.cleaningwc(finalData, id, WaitingActivity.this);
                    } else if (merchanttype.equals("6")) {//苦力商家

                    } else if (merchanttype.equals("7")) {//快递商家

                    } else if (merchanttype.equals("8")) {//家政商家
                        HttpClient.cleaningwc(finalData, id, WaitingActivity.this);
                    } else if (merchanttype.equals("9")) {//洗车商家

                    }

                } else {
                    ToastUtils.Toastshow(context, getResources().getString(R.string.network));
                }
                alertDialog.dismiss();
            }
        }, "确定", "取消");

    }

    @Override
    public void onSuccess(String result) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        System.out.println("stringmd5result" + result);
        List<MerchantsTypeModel> getnote = JsonTools.getmerchanttype(result);
        if (getnote != null || getnote.size() > 0) {
            String error = getnote.get(0).getError();
            String mssage = getnote.get(0).getMssage();
            if (error.equals("200")) {
                String content = getnote.get(0).getResult();
                if (Judge_interface.equals("0")) {//商家中心数据
                        processcleaning(content);
                    available_layout.setVisibility(View.GONE);
                } else if (Judge_interface.equals("1")) {//接单
                    processdata();
                } else if (Judge_interface.equals("2")) {//完成
                    processdata();
                }
            } else if (error.equals("105")) {
                Intent intent = new Intent(context, LoginActivity.class);
                startActivity(intent);
                ToastUtils.show(context, mssage);
            }else if (error.equals("100")){
                if (Judge_interface.equals("0")) {//商家中心数据
                    available_layout.setVisibility(View.VISIBLE);
                }
                ToastUtils.show(context, mssage);
            }else if (error.equals("150")){
                if (Judge_interface.equals("0")) {//商家中心数据
                    available_layout.setVisibility(View.GONE);
                }
                ToastUtils.show(context, mssage);
            } else {
                if (Judge_interface.equals("0")) {//商家中心数据
                    available_layout.setVisibility(View.VISIBLE);
                }
                ToastUtils.show(context, mssage);
            }
        }
        if (Judge_interface.equals("0")){
            xlistview.onPullDownRefreshComplete();
            xlistview.onPullUpRefreshComplete();
            setLastUpdateTime();
        }
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        System.out.println("stringmd5result" + ex.getMessage().toString());
        if (Judge_interface.equals("0")) {//商家中心数据
            available_layout.setVisibility(View.VISIBLE);

                xlistview.onPullDownRefreshComplete();
                xlistview.onPullUpRefreshComplete();
                setLastUpdateTime();


        }
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onCancelled(CancelledException cex) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        System.out.println("stringmd5result" + cex.getMessage().toString());
        if (Judge_interface.equals("0")) {//商家中心数据
            available_layout.setVisibility(View.VISIBLE);

                xlistview.onPullDownRefreshComplete();
                xlistview.onPullUpRefreshComplete();
                setLastUpdateTime();

        }
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onFinished() {

    }

    private void processcleaning(String content) {
        buycarlist.clear();
         getwjcleaningorder = JsonTools.getwjcleaningorder(content);
        if (getwjcleaningorder != null || getwjcleaningorder.size() > 0) {
            WaitingModel Model;
            Double Unitprice = 0.0;
            int Quantity = 0;
            String Productname = "";
            for (int i = 0; i < getwjcleaningorder.size(); i++) {
                Model = new WaitingModel();
                WaitingModel waitingModel = getwjcleaningorder.get(i);
                Model.setId(waitingModel.getId());//id
                Model.setAddtime(waitingModel.getAddtime());//时间
                Model.setOrdername(waitingModel.getOrdername());//
                Model.setOrdernumber(waitingModel.getOrdernumber());//订单号

                if (merchanttype.equals("1")) {//买房商家
                    Model.setOrdermoney(waitingModel.getOrdermoney());//订单金额
                } else if (merchanttype.equals("2")) {//购车商家
                    Model.setOrdermoney(waitingModel.getOrdermoney());//订单金额
                } else if (merchanttype.equals("3")||merchanttype.equals("5")) {//干洗商家 果蔬商家
                    Unitprice = 0.0;
                    Quantity = 0;
                    Productname = "";
                    List<WaitingModel> getwjcleaningorderdetails = JsonTools.getwjcleaningorderdetails(waitingModel.getDetails());
                    if (getwjcleaningorderdetails != null || getwjcleaningorderdetails.size() > 0) {
                        for (int j = 0; j < getwjcleaningorderdetails.size(); j++) {
                            System.out.println("stringmd5result" + getwjcleaningorderdetails.get(j).getProductname());
                            if (Productname.equals("")) {
                                Productname = getwjcleaningorderdetails.get(j).getProductname();
                            } else {
                                Productname = Productname + "," + getwjcleaningorderdetails.get(j).getProductname();
                            }
                            if (Quantity == 0) {
                                Quantity = Integer.valueOf(getwjcleaningorderdetails.get(j).getQuantity());
                            } else {
                                Quantity = Quantity + Integer.valueOf(getwjcleaningorderdetails.get(j).getQuantity());
                            }
                            double quantity = Double.valueOf(getwjcleaningorderdetails.get(j).getQuantity());
                            double unitprice = Double.valueOf(getwjcleaningorderdetails.get(j).getUnitprice());
                            if (Unitprice == 0.0) {
                                Unitprice = quantity * unitprice;
                            } else {
                                Unitprice = Unitprice + quantity * unitprice;
                            }
                        }
                    }
                    DecimalFormat format = new DecimalFormat(",##0.00");
                    String Totalprice = format.format(Unitprice);
                    Model.setUnitprice(Totalprice);//总价
                    Model.setQuantity(Quantity + "");//总数
                    Model.setProductname(Productname);//名称
                } else if (merchanttype.equals("4")) {//开锁商家
                    Model.setOrdermoney(waitingModel.getOrdermoney());//订单金额
                } else if (merchanttype.equals("6")) {//苦力商家
                    Model.setOrdermoney(waitingModel.getOrdermoney());//订单金额
                } else if (merchanttype.equals("7")) {//快递商家

                } else if (merchanttype.equals("8")) {//家政商家
                    Model.setOrdermoney(waitingModel.getOrdermoney());//订单金额
                    Model.setServicetime(waitingModel.getServicetime());//订单金额单位

                } else if (merchanttype.equals("9")) {//洗车商家
                    Model.setOrdermoney(waitingModel.getOrdermoney());//订单金额
                }

                if (!pos.equals("0")) {
                    Model.setOrderstate(waitingModel.getOrderstate());
                }
                buycarlist.add(Model);
            }
            adapter.addItem(buycarlist);
            if (adapter.number()>7){//大于7条时可以上拉加载
                xlistview.setPullLoadEnabled(false);
                xlistview.setScrollLoadEnabled(true);
        }
        }
    }
}
